import React, { useState } from 'react'

export default function CounterUpdate({setCount, count}) {
  const [num, setNum] = useState(1)

  // 增加
  const increment = () => {
    setCount(count + num)
  }
  // 减少
  const decrement = () => {
    setCount(val => val - num)
  }
  // 奇数增加
  const incrementIfOdd = () => {
    if (count%2 === 1) {
      setCount(count + num)
    }
  }
  // 延迟增加
  const incrementAsync = () => {
    setTimeout(() => {
      // setCount(根据原有计算出来value) => 在异步更新中不合适
      // setCount(count + num)  // 有可能是错误
      setCount(val => val + num)
    }, 5000);
  }

  return (
    <div>
      <select value={num} onChange={e => setNum(e.target.value * 1)}>  {/* *1保证num是数值 */}
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
      <button onClick={increment}>增加</button>
      <button onClick={decrement}>减少</button>
      <button onClick={incrementIfOdd}>奇数增加</button>
      <button onClick={incrementAsync}>延迟1S增加</button>
    </div>
  )
}
